﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace OrderManage
{
    public class OrderService
    {
        private List<Order> _orders = new List<Order>();

        //添加新订单
        public void AddOrder(Order order)
        {
            if (_orders.Contains(order)) {
                throw new InvalidOperationException("订单已存在");
            };
            _orders.Add(order);
        }

        //删除订单(根据订单号)
        public void DeleteOrder(int orderId)
        {
            var order = _orders.FirstOrDefault(o => o.OrderId == orderId);
            if (order == null) {
                throw new InvalidOperationException("订单不存在");
            };
            _orders.Remove(order);
        }

        //修改订单
        public void UpdateOrder(Order order)
        {
            var oldOrder = _orders.FirstOrDefault(o => o.OrderId == order.OrderId);
            if (oldOrder == null) {
                throw new InvalidOperationException("订单不存在");
            };
            _orders.Remove(oldOrder);
            _orders.Add(order);
        }

        //获取所有订单
        //根据订单号获取订单
        public IEnumerable<Order> GetByOrderId(int orderId) =>
            _orders.Where(o => o.OrderId == orderId).OrderBy(o => o.TotalAmount);

        //根据生产名获取订单
        public IEnumerable<Order> GetByProduceName(string produceName) =>
            _orders.Where(o => o.Details.Any(d => d.ProduceName == produceName)).OrderBy(o => o.TotalAmount);

        //根据顾客名获取订单
        public IEnumerable<Order> GetByCustomer(string customer) =>
            _orders.Where(o => o.Customer == customer).OrderBy(o => o.TotalAmount); 

        //根据订单状态获取订单
        public IEnumerable<Order> GetByTotalAmount(decimal min, decimal max) =>
            _orders.Where(o => o.TotalAmount >= min &&
                               o.TotalAmount <= max).OrderBy(o => o.OrderId);

        //默认按订单号排序
        public void SortOrder(Comparison<Order> comparison = null) =>
            _orders.Sort(comparison ?? ((a,b) => a.OrderId.CompareTo(b.OrderId)));

        //XML序列化
        public void Export(string path)
        {
            using var writer = new StreamWriter(path);
            new XmlSerializer(typeof(List<Order>)).Serialize(writer, _orders);
        }

        //XML反序列化
        public void Import(string path)
        {
            using var reader = new StreamReader(path);
            _orders = (List<Order>)new XmlSerializer(typeof(List<Order>)).Deserialize(reader)!;
        }
    }
}
